package com.example.administrator.myphoto;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.example.administrator.myphoto.utils.FileUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.io.File;
import java.net.URI;

public class MainActivity extends AppCompatActivity {
    public static final int PHOTO_CODE = 555;


    @ViewInject(R.id.btn1)
    private Button btn1;
    @ViewInject(R.id.btn2)
    private Button btn2;
    @ViewInject(R.id.img)
    private ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);
    }

    @OnClick({R.id.btn1, R.id.btn2})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                startPhoto();
                break;
            case R.id.btn2:
                photoToPath();
                break;
        }
    }

    /*
     *指定路径拍照
     */
    private void photoToPath() {
        File file= FileUtils.getRootCache(this);
        if (file!=null){
            Uri uri= Uri.fromFile(file);
            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
            startActivity(intent);
        }
    }

    /**
     * 启动系统相机拍照
     */
    private void startPhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, PHOTO_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_CODE) {
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            if (bitmap != null) {
                img.setImageBitmap(bitmap);
            }
        }
    }
}
